package com.loan.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.loan.common.enums.SmsTemplateType;
import com.loan.common.exception.ServiceException;
import com.loan.common.utils.StringUtils;
import com.loan.system.domain.ApplyEntity;
import com.loan.system.domain.ApplyProductEntity;
import com.loan.system.domain.CompanyEntity;
import com.loan.system.domain.ExamineLogEntity;
import com.loan.system.mapper.ApplyMapper;
import com.loan.system.mapper.ApplyProductMapper;
import com.loan.system.mapper.CompanyMapper;
import com.loan.system.mapper.ExamineLogMapper;
import com.loan.system.service.ExamineLogService;
import com.loan.system.service.SmsTemplateService;
import com.loan.system.service.UserCompanyService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author shiguang on 2022/9/7 15:45
 */
@RequiredArgsConstructor
@Service
public class ExamineLogServiceImpl implements ExamineLogService {

    private final ExamineLogMapper examineLogMapper;

    private final ApplyMapper applyMapper;

    private final ApplyProductMapper applyProductMapper;

    private final CompanyMapper companyMapper;

    private final SmsTemplateService smsTemplateService;

    private final UserCompanyService userCompanyService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void examineOneApply(String ids, String remark, Integer frozenDay) {
        List<Long> list = Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        for (Long id : list) {
            ApplyEntity applyEntity = applyMapper.selectById(id);
            ExamineLogEntity entity = new ExamineLogEntity();
            entity.setApplyId(id);
            entity.setStatus("2");
            entity.setType("0");
            entity.setRemark(remark);
            entity.setCreateTime(new Date());
            entity.setCompanyId(applyEntity.getCompanyId());
            entity.setUserId(applyEntity.getUserId());
            examineLogMapper.insert(entity);

            //修改订单状态
            applyEntity.setStatus("1");
            applyEntity.setFirstAuditTime(new Date());
            applyMapper.updateById(applyEntity);
            if (applyEntity.getStatus().equals("1") && frozenDay > 0) {
                userCompanyService.save(applyEntity, frozenDay);
            }
        }
    }

    /**
     * 批量通过初审订单
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void examineSuccessOneApply(String ids) {
        List<Long> list = Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        for (Long id : list) {
            ApplyEntity applyEntity = applyMapper.selectById(id);
            ExamineLogEntity entity = new ExamineLogEntity();
            entity.setApplyId(id);
            entity.setStatus("1");
            entity.setType("0");
            entity.setCreateTime(new Date());
            entity.setCompanyId(applyEntity.getCompanyId());
            entity.setUserId(applyEntity.getUserId());
            examineLogMapper.insert(entity);

            //修改订单状态
            applyEntity.setStatus("2");
            applyEntity.setFirstAuditTime(new Date());
            applyMapper.updateById(applyEntity);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void examineTwoApply(String ids, String remark, Integer frozenDay) {
        List<Long> list = Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        for (Long id : list) {
            ApplyEntity applyEntity = applyMapper.selectById(id);
            ExamineLogEntity entity = new ExamineLogEntity();
            entity.setApplyId(id);
            entity.setStatus("2");
            entity.setType("1");
            entity.setRemark(remark);
            entity.setCreateTime(new Date());
            entity.setCompanyId(applyEntity.getCompanyId());
            entity.setUserId(applyEntity.getUserId());
            examineLogMapper.insert(entity);
            //修改订单状态
            applyEntity.setStatus("3");
            applyEntity.setSecondAuditTime(new Date());
            applyMapper.updateById(applyEntity);

            if (applyEntity.getStatus().equals("3") && frozenDay > 0) {
                userCompanyService.save(applyEntity, frozenDay);
            }
        }
    }

    /**
     * 根据用户id获取用户审核记录
     *
     * @param userId
     * @return
     */
    @Override
    public List<ExamineLogEntity> getExamineLogList(Long userId) {
        return examineLogMapper.getExamineLogList(userId);
    }

    @Override
    public int examineApply(JSONObject jsonObject) {
        ApplyEntity entity = applyMapper.selectById(jsonObject.getLong("id"));
        String status = jsonObject.getString("status");
        if (entity != null) {
            if (status.equals("1")) {
                if (entity.getStatus().equals("0")) {
                    entity.setFirstAuditTime(new Date());
                    entity.setStatus("2");
                } else if (entity.getStatus().equals("2")) {
                    Long productId = jsonObject.getLong("productId");
                    if (productId == null) {
                        throw new ServiceException("params is null");
                    }
                    ApplyProductEntity productEntity = applyProductMapper.selectById(productId);
                    entity.setRealApplyMoney(productEntity.getApplyMoney());
                    entity.setApplyCycle(productEntity.getApplyCycle());
                    entity.setApplyServiceCharge(productEntity.getServiceMoney());
                    entity.setManageMoney(productEntity.getManageMoney());
                    entity.setRiskMoney(productEntity.getRiskMoney());
                    entity.setDayRate(productEntity.getDayRate());
                    entity.setExpireRate(productEntity.getExpireRate());
                    entity.setStatus("4");
                    entity.setSecondAuditTime(new Date());
                }
            } else {
                if (entity.getStatus().equals("0")) {
                    entity.setStatus("1");
                    entity.setFirstAuditTime(new Date());
                } else if (entity.getStatus().equals("2")) {
                    entity.setStatus("3");
                    entity.setSecondAuditTime(new Date());
                }
            }
        }
        int count = applyMapper.updateById(entity);
        if (entity.getStatus().equals("4")){
            CompanyEntity companyEntity = companyMapper.selectById(entity.getCompanyId());
            Map params = new HashMap();
            params.put("companyName", "(" + companyEntity.getName() + ")");
            smsTemplateService.sendSms(StringUtils.checkPhone(entity.getUserPhone()), SmsTemplateType.WAIT_WITHDRAWN.getCode(), params);
        }
        ExamineLogEntity examineLogEntity = new ExamineLogEntity();
        examineLogEntity.setStatus(status.equals("1") ? "1" : "2");
        examineLogEntity.setType(entity.getStatus().equals("1") || entity.getStatus().equals("2") ? "0" : "1");
        examineLogEntity.setUserId(entity.getUserId());
        examineLogEntity.setApplyId(entity.getId());
        examineLogEntity.setCompanyId(entity.getCompanyId());
        examineLogEntity.setCreateTime(new Date());
        examineLogEntity.setRemark(jsonObject.getString("remark"));

        examineLogMapper.insert(examineLogEntity);
        //是否冻结
        if (status.equals("2") && jsonObject.getInteger("frozenDay") > 0) {
            //保存冻结记录
            userCompanyService.save(entity, jsonObject.getInteger("frozenDay"));
        }
        return count;
    }


}
